import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
import {MainService} from '../../services/main.service';
import {NzMessageService} from 'ng-zorro-antd/message';
import {LocalStorageService} from '../../../share/local-storage.service';
import {ReloginService} from '../../../share/relogin.service';
import {GlobalAjaxService} from '../../../services/global-ajax.service';
import {NzModalService} from 'ng-zorro-antd/modal';


interface MensNodeInterface {
  children: Array<MensNodeInterface>;
  id: number;
  name: string;
  parentId: number;
  tips: string;
  type: number;
  url: string;
}

@Component({
  selector: 'app-mens',
  templateUrl: './mens.component.html',
  styleUrls: ['./mens.component.css']
})
export class MensComponent implements OnInit {
  public mens: Array<MensNodeInterface> = [];
  public isOkLogining = false;
  public passwordVisible = false;
  public isLogin = false;
  public userInfo = {username: '', password: '', nickname: ''};
  public showUserInfo = {username: '', nickname: ''};
  constructor(
    public relogin: ReloginService,
    private mainService: MainService,
    private message: NzMessageService,
    private router: Router,
    private localStorage: LocalStorageService,
    private gas: GlobalAjaxService,
    private modal: NzModalService,
  ) { }

  ngOnInit(): void {
    this.updateMens();
    this.relogin.localStoregeUserInfoChange.subscribe({next: (data) => {
      this.showUserInfo = data.userInfo;
      if (data.userInfo.username) { this.isLogin = true; }
      this.updateMens();
    }});
    this.gas.isTokenInvalid.subscribe({next: () => {
      this.router.navigateByUrl('/main/home');
      this.relogin.showLoginModal();
      this.updateMens();
      this.isLogin = false;
    }});
  }

  showModal(): void {
    this.relogin.showLoginModal();
  }

  handleCancel(): void {
    this.relogin.hideLoginModal();
  }

  public updateMens(): void {
    this.mainService.getPrjMens({name: '你爹'}, (res) => {
      this.mens = res.content;
      this.isLogin = false;
      for (const vo of this.mens) {
        if (vo.id === 5) {
          this.showUserInfo = JSON.parse(this.localStorage.get(this.relogin.localStoregeUserInfoKey));
          this.isLogin = true;
          break;
        }
      }
    }, (err) => {
      console.log(err);
    });
  }

  public doLogin(): void {
    this.relogin.doLogin(this.userInfo, (res) => {
      this.showUserInfo = res;
      this.isOkLogining = false;
    }, (err) => {
      this.isOkLogining = false;
    });
  }

  public logout(): void {
    this.modal.confirm({
      nzTitle: '您是否确认退出?',
      nzContent: '',
      nzOkText: '退出',
      nzOkType: 'default',
      nzOnOk: () => {
        this.isLogin = false;
        this.relogin.logOut();
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }
}
